//
//  GameLayer.m
//  618
//
//  Created by Ling on 13-6-21.
//  Copyright 2013年 __618工作室__. All rights reserved.
//

#import "GameLayer.h"
#import "BallSprite.h"
#import "Score.h"
#import "saveGame.h"
#import "FindAndDel.h"

#import "CCTouchDispatcher.h"
#import "PathStep.h"

#import "BlockAlertView.h"
#import "BlockActionSheet.h"
#import "BlockTextPromptAlertView.h"


#define maxX MAX_ROWS +1
#define maxY  MAX_COLS +1
#define widthPadding WIDTH_PADING
#define heightPadding HEIGHT_PADING
#define ballWidth ROWS_WIDTH
#define Delaytime ((NSTimeInterval)0.5)

@interface GameLayer()
- (void)findMatchBall:(BallSprite *)currentBall;
- (void) addThreeBall;
- (void) delBall:(BallSprite *)ballSprite;
- (void)findMatchBall:(BallSprite *)currentBall isSystem:(bool)isSystem;

@end

@implementation GameLayer
@synthesize delegate;
@synthesize background,statusBar,over,ballArray,num,selected,scoreLabel,hightScoreLabel,score,ballpre;
@synthesize tipSprite;
@synthesize tipPoint;
-(id) init
{
	self = [super init];
	
	if (self)
	{
        
        //游戏加载
        //添加ball
        Log_Debug(@"游戏初始化");
        
        CGSize size = [[CCDirector sharedDirector] winSize];
        Log_Debug(@"winSize:[%f,%f]",size.width,size.height);
        NSString *fileName;
        if (IS_Ipad) {
            fileName = @"bg1.png";
            
        }
        else
        {
            fileName = @"bg1.jpg";
            
        }
        
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"bg.plist"];
        CCSprite *back = [CCSprite spriteWithSpriteFrameName:fileName];
        back.opacity = 200.0f;
        back.position = ccp(size.width/2,size.height/2);
        self.background = back;
		[self addChild:background z:0];
        
        
        //添加ball
        NSString *sSheet,*sPlist;
        sSheet = @"ballList.png";
        sPlist = @"ballList.plist";
        // Load sprites
        spriteNode = [CCSpriteBatchNode batchNodeWithFile:sSheet];
        
        [self addChild:spriteNode z:1];
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:sPlist];
        
        
        //添加状态记分栏
        NSString *barPlist = @"bar.plist";
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:barPlist];
        CCSprite *status = [CCSprite  spriteWithSpriteFrameName:@"statusBar.png"];
        self.statusBar = status;
        if (IS_Ipad) {
            status.position = ccp(size.width/2,size.height-35);
        }
        else
        {
            status.position = ccp(size.width/2,size.height-16);
        }
        
        [self addChild:status z:2];
        
        
        CCLabelTTF *label = [CCLabelTTF labelWithString:@"分数:0" fontName:@"ArialRoundedMTBold" fontSize:16];
        label.color = ccBLACK;
        label.horizontalAlignment = kCCTextAlignmentRight;
        
        label.position = ccp(size.width-70, self.statusBar.position.y*2- size.height-12);
        
        if (IS_Ipad) {
            label.fontSize = 20;
            label.position = ccp(size.width-100, self.statusBar.position.y*2- size.height-12);
        }
        
        self.scoreLabel = label;
        CGSize s = CGSizeMake(100, 24);
		[self setContentSize: s];
        [self addChild:scoreLabel z:3];
        [label release];
        
        CCLabelTTF *hightlabel = [CCLabelTTF labelWithString:@"最高分数:0" fontName:@"ArialRoundedMTBold" fontSize:16];
        hightlabel.color = ccBLACK;
        hightlabel.horizontalAlignment = kCCTextAlignmentRight;
        if (IS_Ipad) {
            hightlabel.fontSize = 20;
        }
        self.hightScoreLabel = hightlabel;
        CGSize ss = CGSizeMake(100, 24);
		[self setContentSize: ss];
        hightScoreLabel.position = ccp(70,self.statusBar.position.y*2- size.height-12);
		[hightlabel release];
		[self addChild:hightScoreLabel z:3];
        
        //添加状态记分栏
        NSString *backPlist = @"back.plist";
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:backPlist];
        CCSprite *backball = [CCSprite  spriteWithSpriteFrameName:@"back.png"];
        backball.position = ccp(ballWidth+30,heightPadding/2);
        [self addChild:backball z:3];
		
        NSMutableArray *array = [[NSMutableArray alloc] init];
        self.ballArray = array;
        [array release];
        
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        self.num = arr;
        [arr release];
        self.selected = -1;
        self.isTouchEnabled = YES;
        [[[CCDirector sharedDirector] touchDispatcher]  addTargetedDelegate:self priority:0 swallowsTouches:YES];
        isClickAbled = YES;
        
        NSMutableArray *arraypre = [[NSMutableArray alloc] init];
        self.ballpre = arraypre;
        [arraypre release];
        [self addThreeBallpre];
        
        emptyArr = [[NSMutableArray alloc] init];
        for (int i=0;i< maxX;i++) {
            for (int j=0;j< maxY;j++) {
                
                NSValue *emptypoint = [NSValue valueWithCGPoint:ccp(i,j)];
                [emptyArr addObject:emptypoint];
            }
        }
        
        tipSprite = [CCSprite spriteWithFile:@"point.png"];
        tipSprite.zOrder = 100000;
        [self addChild:tipSprite];
        
        //加载最高分数列表
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        NSData * topScores = [defaults objectForKey:@"topScores"];
        if (topScores) {
            scoreArr = [[NSKeyedUnarchiver unarchiveObjectWithData:topScores] retain];
            [self setTopScore];
        }
        else
        {
            scoreArr = [[NSMutableArray alloc] init];
        }
        
    }
    return self;
}

//画线
-(void)draw
{
    
    glColorMask(240, 240, 240, 240);
    if (IS_Ipad) {
        glLineWidth(2);
    }
    else
    {
        glLineWidth(1);
    }
    int x = maxX;
    int y = maxY;
    
    for (int i=0;i<y+1;i++) {
        CGPoint esquina1 = ccp(widthPadding+ballWidth*i,heightPadding+ballWidth*y);
        CGPoint esquina2 = ccp(widthPadding+ballWidth*i,heightPadding);
        ccDrawLine(esquina1, esquina2);
    }
    
    for (int i=0;i<x+1;i++) {
        CGPoint esquina1 = ccp(widthPadding,heightPadding+ballWidth*i);
        CGPoint esquina2 = ccp(widthPadding+ballWidth*x,heightPadding+ballWidth*i);
        ccDrawLine(esquina1, esquina2);
    }
    
}

//随机位置生成
- (CGPoint) randomPoint
{
    Log_Debug(@"randomPoint... start ...");
    int random = [self randomBall:emptyArr.count];
    Log_Debug(@"random = %d",random);
    //[emptyArr objectAtIndex:random];
    CGPoint  ranPoint = [[emptyArr objectAtIndex:random] CGPointValue];
    [emptyArr removeObjectAtIndex:random];
    Log_Debug(@"randomPoint... end ...");
    return ranPoint;
}
//随机类型数生成
- (int) randomBall:(int) index
{
    Log_Debug(@"randomBall... start ...");
    int random = (arc4random() % index);
    Log_Debug(@"randomBall... end ...");
	return random;
}
//添加预加载三个显示ball
-(void)addThreeBallpre
{
    Log_Debug(@"addThreeBallpre... start ...");
    for(int i = 0; i < 3; i++)
    {
        int typenum = 6;
        //        if (IS_Ipad) {
        //            typenum = 6;
        //        }
        int randomBallNum = [self randomBall:typenum];
        NSString *ballName = [NSString stringWithFormat:@"%d_up.png",randomBallNum+1];
        Log_Debug(@"ballName = %@",ballName);
        if ([self.ballpre count]<3) {
            BallSprite *sp = [BallSprite spriteWithSpriteFrameName:ballName];
            CGSize size = [[CCDirector sharedDirector] winSize];
            sp.position = ccp(size.width/2-(ballWidth+2)*(i-1),self.statusBar.position.y);
            sp.x = sp.position.x;
            sp.y = sp.position.y;
            sp.type = randomBallNum+1;
            sp.del = NO;
            sp.tag = i;
            
            [self addChild:sp  z:4];
            [self.ballpre addObject:sp];
            
        }
        else
        {
            BallSprite *sp = [self.ballpre objectAtIndex:i];
            CCSpriteFrame* frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:ballName];
            [sp setDisplayFrame:frame];
            sp.type = randomBallNum+1;
            
        }
    }
    Log_Debug(@"addThreeBallpre... end ...");
}

//随机生成三个球

- (void) addThreeBall
{
    Log_Debug(@"addThreeBall... start ...");
    isClickAbled = YES;
     Log_Debug(@"添加三个随机球");
    for(int i = 0; i < 3; i++)
    {
        BallSprite *ballsprie = [self.ballpre objectAtIndex:i];
        NSString *ballName = [NSString stringWithFormat:@"%d_up.png",ballsprie.type];
        Log_Debug(@"ballName = %@",ballName);
        //BallSprite *sp = [[BallSprite alloc] initWithFile:ballName];
        BallSprite *sp = [BallSprite spriteWithSpriteFrameName:ballName];
        CGPoint point = [self randomPoint];
        CGPoint ranPoint = [self convertPoint:point];
        sp.position = ccp(ranPoint.x, ranPoint.y);
        sp.x = point.x;
        sp.y = point.y;
        sp.type = ballsprie.type;
        sp.del = NO;
        sp.tag = 10*point.x + point.y;
        [sp load];
        [spriteNode addChild:sp];
        [self.ballArray addObject:sp];
        Log_Debug(@"添加一个[%d]号球 [%d,%d]",sp.type,sp.x,sp.y);
        if ([self.ballArray count]>80) {
            [self endGame];
            return;
        }
        if ([self.ballArray count]>4) {
            // [self performSelector:@selector(findMatchBall:) withObject:sp afterDelay:0.3];
            [self findMatchBall:sp isSystem:YES];
            isClickAbled = YES;
            
        }
        
    }
    //添加预加载ball
    [self addThreeBallpre];
    Log_Debug(@"addThreeBall... end ...");
    
}
- (void)findMatchBall:(BallSprite *)currentBall
{
    [self findMatchBall:currentBall isSystem:NO];
}
- (void)findMatchBall:(BallSprite *)currentBall isSystem:(bool)isSystem
{
    Log_Debug(@"findMatchBall... start ...");
    
    NSMutableArray *temparray = [FindAndDel findMatchBall:currentBall currentAdded:self.ballArray];
    //so the ball need to delete is :
    int iCount = temparray.count;
    
    BOOL bDeleteCurrent = NO;
    int delCount = 0;
    for (int i=0; i<iCount;++i) {
        BallSprite *sp = (BallSprite *)[temparray objectAtIndex:i];
        if (sp.del) {
            Log_Debug(@"The ball [%d,%d] need to del.",sp.x,sp.y);
            
            [self delBall:sp];
            bDeleteCurrent = YES;
            delCount++;
        }
        
    }
    if(bDeleteCurrent)
    {
        [self delBall:currentBall];
        //计算分数
        if (delCount>4) {
            self.score = 10 + 5*(delCount - 4);
        }
        else
        {
            self.score = 2*(delCount + 1);
        }
        Log_Debug(@"得分:[%d]",self.score);
    }
    if (!isSystem && !bDeleteCurrent) {
        //添加三个球
        [self addThreeBall];
        //[self performSelector:@selector(addThreeBall) withObject:nil afterDelay:0];
    }
    
    isClickAbled = YES;
    Log_Debug(@"findMatchBall... end ...");
}

- (void) delBall:(BallSprite *)ballSprite
{
    Log_Debug(@"delBall... start ...");
    NSValue *emptypoint = [NSValue valueWithCGPoint:ccp(ballSprite.x,ballSprite.y)];
    [emptyArr addObject:emptypoint];
    [self.ballArray removeObject:ballSprite];
    [ballSprite remove];
    [self performSelector:@selector(removeBall:) withObject:ballSprite afterDelay:0.3];
    //[self removeBall:ballSprite];
    Log_Debug(@"delBall... end ...");
    self.selected = -1;
}

- (void) removeBall:(BallSprite *)ballSprite
{
    Log_Debug(@"removeBall... start ...");
    if (ballSprite) {
        [spriteNode removeChild:ballSprite cleanup:YES];
        
    }

    Log_Debug(@"removeBall... end ...");
    
}


//游戏结束
-(void)returnMenu
{
    Log_Debug(@"returnMenu... start ...");
    gameOver = YES;
    [self removeChild:self.over cleanup:YES];
    [self cleanupAllBall];
    [self saveGames];
	if ([self.delegate respondsToSelector:@selector(endGame)])
	{
		[self.delegate endGame];
	}
    Log_Debug(@"returnMenu... end ...");
}

- (void) endGame
{
    Log_Debug(@"endGame... start ...");
	Log_Debug(@"游戏结束");
    
    gameOver = YES;
    if(over == nil) {
        CGSize size = [[CCDirector sharedDirector] winSize];
        CCSprite *oversp = [[CCSprite alloc] initWithFile:@"game_over.png"];
        self.over = oversp;
        over.position = ccp(size.width/2,size.height/2);
        [oversp release];
    }
    [self addChild:over z:5];
    if ([scoreArr count]<10 ) {
        [self showTextPrompt];
        return;
    }
    else
    {
        Score * topscores = (Score *)[scoreArr lastObject];
        if (topscores.score<score) {
            [self showTextPrompt];
            return;
        }
    }
    [self performSelector:@selector(returnMenu) withObject:nil afterDelay:1.8];
    
    Log_Debug(@"endGame... end ...");
}

//清盘
- (void) cleanupAllBall
{
    Log_Debug(@"cleanupAllBall... start ...");
    
    [self.ballArray removeAllObjects];
    [emptyArr removeAllObjects];
    for (int i=0;i< maxX;i++) {
        for (int j=0;j< maxY;j++) {
            
            NSValue *emptypoint = [NSValue valueWithCGPoint:ccp(i,j)];
            [emptyArr addObject:emptypoint];
        }
    }

    [spriteNode removeAllChildrenWithCleanup:YES];
    score = 0;
    self.score = 0;
    Log_Debug(@"cleanupAllBall... end ...");
}



//游戏开始
- (void) restartGame
{
	Log_Debug(@"游戏开始");
    Log_Debug(@"restartGame... start ...");
   
    gameOver = NO;
    [self cleanupAllBall];
    [self addThreeBall];
    //[self schedule:@selector(addThreeBall:) interval:3.5];
    [self setTopScore];
    Log_Debug(@"restartGame... end ...");
    
}
- (void) saveGames
{
    Log_Debug(@"saveGames... start ...");
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    Log_Debug(@"savescore = %d",self.score);
    
    NSMutableArray *saveArr = [[NSMutableArray alloc] init];
    saveGame *tempSave = [[saveGame alloc] init];
    tempSave.name = @"保存棋局";
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *now = [dateFormatter stringFromDate:today];
    
    tempSave.recordTime = now;
    tempSave.score = self.score;
    tempSave.ballArray = self.ballArray;
    [saveArr addObject:tempSave];
    
    [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:saveArr] forKey:@"lastGames"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [dateFormatter release];
    [tempSave release];
    [saveArr release];
    Log_Debug(@"saveGames... end ...");
}

- (void) continueGames
{
    Log_Debug(@"continueGames... start ...");
    
    gameOver = NO;
    [self cleanupAllBall];
    [self setTopScore];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSData * balldetail = [defaults objectForKey:@"lastGames"];
    if (balldetail) {
        if (ballArray) {
            [ballArray removeAllObjects];
        }
        Log_Debug(@"xxxx = %@",[NSKeyedUnarchiver unarchiveObjectWithData:balldetail]);
        
        NSMutableArray *saveGameArraytemp = [NSKeyedUnarchiver unarchiveObjectWithData:balldetail];
        Log_Debug(@"save count = %d",[saveGameArraytemp count]);
        saveGame *savegame = [saveGameArraytemp lastObject];
        self.score = savegame.score;
        NSMutableArray *ballArraytemp = savegame.ballArray;
         Log_Debug(@"save ball count = %d",[ballArraytemp count]);
        for (int i=0;i<[ballArraytemp count];++i) {
            BallSprite *tempSp = [ballArraytemp objectAtIndex:i];
            
            Log_Debug(@"x = %d",tempSp.x);
            Log_Debug(@"y = %d",tempSp.y);
            Log_Debug(@"type = %d",tempSp.type);
            Log_Debug(@"score = %d",tempSp.score);
            
            NSString *ballName = [NSString stringWithFormat:@"%d_up.png",tempSp.type];
            Log_Debug(@"ballName = %@",ballName);
            
            BallSprite *sp = [BallSprite spriteWithSpriteFrameName:ballName];
            CGPoint point = CGPointMake(tempSp.x,tempSp.y);
            CGPoint ranPoint = [self convertPoint:point];
            sp.position = ccp(ranPoint.x, ranPoint.y);
            sp.x = point.x;
            sp.y = point.y;
            sp.type = tempSp.type;
            sp.del = NO;
            sp.tag = 10*ranPoint.x + ranPoint.y;
            [sp load];
            [spriteNode addChild:sp];
            [self.ballArray addObject:sp];
//            if (self.score == 0) {
//                
//            }
            
        }
    }
    Log_Debug(@"self.score = %d",self.score);
    Log_Debug(@"continueGames... end ...");
}
//下一关
- (void) nextLevel
{
            Log_Debug(@"nextLevel... start ...");
    Log_Debug(@"游戏下一关");
    if ([self.delegate respondsToSelector:@selector(nextLevel)])
	{
		[self.delegate nextLevel];
	}
                Log_Debug(@"nextLevel... end ...");
}


// touch action

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
    Log_Debug(@"ccTouchMoved... start ...");
    if (gameOver || !isClickAbled) return;
    if(!IS_Ipad){
        CGPoint touchLocation = [spriteNode convertTouchToNodeSpace:touch];
        
        Log_Debug(@"点击 [%.2f,%.2f]",touchLocation.x,touchLocation.y);
        CGPoint point = [touch locationInView:[touch view ]];
        CGPoint opengl_point=[[CCDirector sharedDirector] convertToGL:point];
        
        if (opengl_point.y < heightPadding ||opengl_point.y > heightPadding+ballWidth*(maxY+0.01)) {
            Log_Debug(@"点击在棋盘之外");
            
            return ;
        }
        else if (opengl_point.x < widthPadding ||opengl_point.x > widthPadding+ballWidth*(maxX+0.01)) {
            Log_Debug(@"点击在棋盘之外");
            
            return ;
        }
        else  if(self.selected > -1)
        {
            int x = (touchLocation.x - widthPadding)/ballWidth;
            int y = (touchLocation.y - heightPadding)/ballWidth;
            
            [self.tipSprite setVisible:YES];
            if(tipPoint.x!=x || tipPoint.y  !=y){
                id tMove = [CCMoveTo actionWithDuration:0.1 position:ccp(x*ballWidth +ballWidth/2 + widthPadding,y*ballWidth + heightPadding  + ballWidth )];
                [tipSprite runAction:tMove];
                tipPoint = CGPointMake(x, y);
            }
            //self.tipSprite.position = ccp(x*ballWidth +ballWidth/2 + widthPadding,y*ballWidth + heightPadding  + ballWidth );
        }
    }
        Log_Debug(@"ccTouchMoved... end ...");
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    Log_Debug(@"ccTouchBegan... start ...");
    if (gameOver || !isClickAbled) return NO;
        return YES;
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
    Log_Debug(@"ccTouchEnded... start ...");
    [tipSprite setVisible:NO];
    if (gameOver || !isClickAbled) return ;
    //CGPoint point = [touch locationInView: [touch view]];
    CGPoint touchLocation = [spriteNode convertTouchToNodeSpace:touch];
    Log_Debug(@"点击 [%.2f,%.2f]",touchLocation.x,touchLocation.y);
    CGPoint point = [touch locationInView:[touch view ]];
    CGPoint opengl_point=[[CCDirector sharedDirector] convertToGL:point];
    
    //ccp(ballWidth+30,heightPadding/2);
    
    if (opengl_point.x > ballWidth-20 && opengl_point.x < ballWidth+80) {
        if (opengl_point.y < heightPadding) {
            //[self showTextPrompt];
            [self showAlert];
            return ;
        }
        
    }
    
    if (opengl_point.y < heightPadding ||opengl_point.y > heightPadding+ballWidth*(maxY+0.01)) {
        Log_Debug(@"点击在棋盘之外");
        
        return ;
    }
    if (opengl_point.x < widthPadding ||opengl_point.x > widthPadding+ballWidth*(maxX+0.01)) {
        Log_Debug(@"点击在棋盘之外");
        return ;
    }
    
    BallSprite * ballpr = nil;
    Log_Debug(@"ccTouchEnded... self.selected=%d self.ballArray.count=%d ...",self.selected,self.ballArray.count);
    if (self.selected > -1) {
        ballpr = (BallSprite *)[self.ballArray objectAtIndex:self.selected];
        [ballpr touchUnSelect];
    }
    BOOL isball = NO;
    
    //Log_Debug(@"touchLocation = %f,%f",touchLocation.x,touchLocation.y);
    for (int i=0;i<[self.ballArray count]; i++) {
        BallSprite * ballsp = (BallSprite *)[self.ballArray objectAtIndex:i];
        CGPoint diff = ccpSub(touchLocation, ballsp.position);
        // Log_Debug(@"diff = %f,%f",diff.x,diff.y);
        if (abs(diff.x)<ballWidth/2&&abs(diff.y)<ballWidth/2) {
            if (self.selected != i) {
                [ballsp touchSelect];
                self.selected = i;
                Log_Debug(@"点击球 [%d,%d]",ballsp.x,ballsp.y);
            }
            else
            {
                
                self.selected = -1;
            }
            isball = YES;
        }
        
    }
    if (!isball) {
        //self.selected = -1;
        if (ballpr) {
            int x = (touchLocation.x - widthPadding)/ballWidth;
            int y = (touchLocation.y - heightPadding)/ballWidth;
            Log_Debug(@"点击空格 [%d,%d]",x,y);
            NSMutableArray* arrClosedPath = [[[NSMutableArray alloc] init] autorelease];
            int iCount = self.ballArray.count;
            for (int i=0; i<iCount; ++i) {
                BallSprite * ballsp = (BallSprite *)[self.ballArray objectAtIndex:i];
                int cellX = ballsp.x;
                int cellY = ballsp.y;
                NSValue *closedPoint = [NSValue valueWithCGPoint:ccp(cellX,cellY)];
                Log_Debug(@"XX closedPoint [%d,%d]",cellX,cellY);
                [arrClosedPath addObject:closedPoint];
                
            }
            //use the A* to find the path
            Log_Debug(@"use the A* to find the path（使用A*算法）");
            PathStep* startStep = [[PathStep alloc] initWithPosition:ccp(ballpr.x,ballpr.y) closedArray:arrClosedPath];
            PathStep* endStep = [[PathStep alloc] initWithPosition:ccp(x,y) closedArray:arrClosedPath];
            NSMutableArray *arrShortestPath =(NSMutableArray *)[endStep findShortestPath:startStep targetCell:endStep closedArray:arrClosedPath];
            if (arrShortestPath==nil || (arrShortestPath!=nil && arrShortestPath.count==0)) {
                CCLOG(@"No way to go there,pls retry!");
                Log_Debug(@"A*算法:无路可走！");
                [ballpr touchSelect];
            }
            else
            {
                NSMutableArray *arrMove = [NSMutableArray array];
                int iMax = arrShortestPath.count;
                Log_Debug(@"A*算法:一共有%d步",iMax);
                for (int i = 0; i < iMax; i++) {
                    PathStep* ps = (PathStep*)[arrShortestPath objectAtIndex:i];
                    Log_Debug(@"[%.2f,%.2f] in cell[%d,%d]",ps.position.x,ps.position.y,ps.cellX,ps.cellY);
                    if(i==0){
                        id move=[CCMoveTo actionWithDuration:.1  position:ccp(ps.position.x,ps.position.y)];
                        [arrMove addObject:move];
                    }else if(i<iMax -1 && iMax<=5)
                    {
                        id move=[CCMoveTo actionWithDuration:.1  position:ccp(ps.position.x,ps.position.y)];
                        [arrMove addObject:move];
                        
                    }
                    else if(i<iMax -1 && iMax>5)
                    {
                        id move=[CCMoveTo actionWithDuration:.05  position:ccp(ps.position.x,ps.position.y)];
                        [arrMove addObject:move];
                    }
                    else
                    {
                        id move=[CCMoveTo actionWithDuration:0.05  position:ccp(ps.position.x,ps.position.y)];
                        [arrMove addObject:move];
                    }
                    
                    Log_Debug(@"A*算法:停留坐标[%.2f,%.2f]",ps.position.x,ps.position.y);
                }
                NSArray *arrayM = [NSArray arrayWithArray:arrMove];
                id seq = [CCSequence actionWithArray:arrayM];
                
                //id move=[CCMoveBy actionWithDuration:1.5  position:ccp(200,200)];
                [ballpr runAction:seq];
                
                
                NSValue *emptypoint = [NSValue valueWithCGPoint:ccp(ballpr.x,ballpr.y)];
                [emptyArr addObject:emptypoint];
                NSValue *fullpoint = [NSValue valueWithCGPoint:ccp(x,y)];
                [emptyArr removeObject:fullpoint];
                
                ballpr.x = x;
                ballpr.y = y;
                Log_Debug(@"A*算法:最终停留格[%d,%d]",ballpr.x,ballpr.y);
                //ballpre.position = [self convertPoint:ranPoint];
                self.selected = -1;
                //遍历所有球，横、竖、斜线，五个相连删除
                if(iMax<=5){
                    [self performSelector:@selector(findMatchBall:) withObject:ballpr afterDelay:iMax*0.1];
                }
                else{
                    [self performSelector:@selector(findMatchBall:) withObject:ballpr afterDelay:iMax*0.05+0.2];
                }
                isClickAbled = NO;
            }
             Log_Debug(@"ccTouchEnded... end ...");
        }
        else
        {
            self.selected = -1;
            Log_Debug(@"ccTouchEnded... end ...");
            return ;
        }
        
    }
    
}


- (CGPoint)convertPoint:(CGPoint)point {
    
    CGPoint convertPoint = CGPointMake(widthPadding+ballWidth*point.x+ballWidth/2, heightPadding+ballWidth*point.y+ballWidth/2);
    
    return convertPoint;
}
- (void) setScore:(int) addScore
{
	score = score + addScore;
    Log_Debug(@"分数:%d",addScore);
    [self.scoreLabel setString:[NSString stringWithFormat:@"分数:%d", score]];
}
- (void) setTopScore
{
	if ([scoreArr count]) {
        Score * topscores = (Score *)[scoreArr objectAtIndex:0];
        [self.hightScoreLabel setString:[NSString stringWithFormat:@"最高分数:%d", topscores.score]];
    }
    
}

- (void)showAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"退出本局" message:@"你确定要退出本局，重新开始吗？退出之后本局所有棋子将不能重现！"];
    
    [alert setCancelButtonWithTitle:@"取消" block:nil];
    [alert addButtonWithTitle:@"确定" block:^{
        [self returnMenu];
    }];
    
    [alert show];
}


- (void)showTextPrompt
{
    UITextField *textField;
    
    BlockTextPromptAlertView *alert = [BlockTextPromptAlertView promptWithTitle:@"恭喜你了！！！" message:@"你真是太棒了，进入前十名，请留下你的名字吧" textField:&textField defaultText:@"你的名字" block:^(BlockTextPromptAlertView *alert){
        
        [alert.textField resignFirstResponder];
        return YES;
    }];
    [alert setCancelButtonWithTitle:@"取消" block:^{
        Log_Debug(@"取消");
        [self performSelector:@selector(returnMenu) withObject:nil afterDelay:0.5];
    }];
    [alert addButtonWithTitle:@"确定" block:^{
        Log_Debug(@"名字: %@", textField.text);
        [self saveSore:textField.text];
        
    }];
    [alert show];
}
-(void)saveSore:(NSString *)name
{
    Score * scores = [[[Score alloc] init] autorelease];
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *now = [dateFormatter stringFromDate:today];
    scores.recordTime = now;
    scores.name = name;
    scores.score = score;
    [dateFormatter release];
    Log_Debug(@"保存分数:%d",score);
    BOOL isadd = NO;
    int scoreArrInt = [scoreArr count];
    for (int i=0; i<scoreArrInt;i++) {
        Score * topscores = (Score *)[scoreArr objectAtIndex:i];
        if (topscores.score < score) {
            [scoreArr insertObject:scores atIndex:i];
            isadd = YES;
            i = scoreArrInt;
        }
    }
    if (!isadd)
    {
        [scoreArr addObject:scores];
    }
    
    if ([scoreArr count]>10) {
        [scoreArr removeLastObject];
    }
    Log_Debug(@"保存分数:%d",[scoreArr count]);
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:scoreArr] forKey:@"topScores"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self setTopScore];
    [self performSelector:@selector(returnMenu) withObject:nil afterDelay:0.5];
    
}
- (void) dealloc
{
	
	[delegate release];
    [background release];
    [statusBar release];
    [ballArray release];
    [emptyArr release];
    self.num = nil;
    self.scoreLabel = nil;
    self.hightScoreLabel = nil;
    self.ballpre = nil;
    [scoreArr release];
	[super dealloc];
}


@end
